<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
               v-if="showMain"
    >
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{type,size,row,index}" slot="menuBtn">
        <el-dropdown-item v-if="row.status === 0 && !row.isUploadScores" divided @click.native="importGrades(row)">上传成绩</el-dropdown-item>
        <el-dropdown-item v-if="row.status === 0 && row.isUploadScores" divided @click.native="importGrades(row)">
          重新上传成绩
        </el-dropdown-item>
        <el-dropdown-item v-if="row.status === 1 && row.isUploadScores" divided @click.native="importGrades(row)"
                          disabled>重新上传成绩
        </el-dropdown-item>
        <el-dropdown-item v-if="row.status === 0 && !row.isUploadScores" divided disabled @click.native="publishGrades(row)">发布成绩</el-dropdown-item>
        <el-dropdown-item v-if="row.status === 0 && row.isUploadScores" divided @click.native="publishGrades(row)">发布成绩</el-dropdown-item>
        <el-dropdown-item v-if="row.status === 1 && row.isUploadScores" divided @click.native="publishGrades(row)">取消发布</el-dropdown-item>
        <el-dropdown-item divided @click.native="showView(row)">成绩列表</el-dropdown-item>
      </template>
    </avue-crud>

    <el-dialog title="成绩导入"
               append-to-body
               :visible.sync="excelBox"
               v-if="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter" :upload-before="uploadBefore"
                 :upload-error="uploadError">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate()">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <gradesList v-bind:csId="csId" :showMainView="showMainView" v-if="(!showMain)&&show" ref="eps1"></gradesList>
  </basic-container>
</template>

<script>
import {getList, add, update, remove, issueOrCancelExamSore} from "@/api/service/grades";
import {mapGetters} from "vuex";
import {contrastTime} from "@/util/validate";
import gradesList from "@/views/service/gradesList.vue";

export default {
  components: {
    gradesList
  },
  data() {
    return {
      showMain: true,
      show: false,
      csId:'',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuType: 'menu',
        menuBtnTitle: '更多操作',
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "考试名称",
            prop: "ksName",
            span: 12,
            search: true,
            rules: [{
              required: false,
              message: "请输入考试名称",
              trigger: "blur"
            }],
            // disabled: true,
            maxlength: 100,
            showWordLimit: true
          },
          {
            label: "学期",
            prop: "xqId",
            search: true,
            rules: [{
              required: true,
              message: "请选择学期",
              trigger: "blur"
            }],
            type: "select",
            span: 12,
            // cascader: ['xnId'],
            dicUrl: "/api/ManageExamScore/GetSchoolSemesterSelect",
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "年级",
            prop: "njId",
            search: true,
            rules: [{
              required: true,
              message: "请选择年级",
              trigger: "blur"
            }],
            type: "select",
            hide: true,
            cascader: ['bjId'],
            span: 12,
            dicUrl: "/api/ManageExamScore/GetTeacherGradeSelect",
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "班级",
            prop: "bjId",
            search: true,
            hide: true,
            rules: [{
              required: true,
              message: "请选择班级",
              trigger: "blur"
            }],
            type: "select",
            cascader: ['kcIds'],
            span: 12,
            dicUrl: "/api/ManageExamScore/GetTeacherClassSelect?njId={{key}}",
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "班级",
            prop: "bjName",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            span: 12,
          },
          {
            label: "参加考试科目",
            prop: "kcIds",
            // search: true,
            hide: true,
            rules: [{
              required: true,
              message: "请选择参加考试科目",
              trigger: "blur"
            }],
            type: "select",
            multiple: true,
            span: 12,
            dicUrl: "/api/ManageExamScore/GetTeacherCourseSelect?bjId={{key}}",
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "参加考试科目",
            prop: "kcNames",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            span: 12,
          },
          {
            label: "考试开始时间",
            prop: "ksStart",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            // search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请选择考试开始时间",
              trigger: "blur"
            }]
          },
          {
            label: "考试结束时间",
            prop: "ksEnd",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            // search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请选择考试结束时间",
              trigger: "blur"
            }]
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            // search: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入报名开始时间",
              trigger: "blur"
            }]
          },
          {
            label: "状态",
            prop: "status",
            type: 'select',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            rules: [{
              required: true,
              message: "请选择是否需要审核",
              trigger: "blur"
            }],
            dicData: [{
              label: '待发布',
              value: 0
            }, {
              label: '已发布',
              value: 1
            }],
            value: 0
          },
        ]
      },
      data: [],
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "第一步: 请点击下面的按钮下载Excel模板，并按照模板填写信息",
            labelWidth: 426,
            type: 'title',
            prop: "title",
            span: 24,
            styles: {
              // color: 'red',
              fontSize: '24px'
            }
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
          {
            formslot: true,
            label: "第二步: 导入Excel模板文件",
            labelWidth: 200,
            type: 'title',
            prop: "title1",
            span: 24,
            styles: {
              // color: 'red',
              fontSize: '24px'
            }
          },
          {
            label: '文件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '导入数据处理需要时间，请耐心等待！',
            accept: ".xls,.xlsx",
            span: 24,
            // propsHttp: {
            //   res: 'data'
            // },
            data: {id: ''},
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/ManageExamScore/ImportExamSoreRecord",
          },

        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: true,//this.vaildData(this.permission.xq_add, false),
        viewBtn: true,//this.vaildData(this.permission.xq_view, false),
        delBtn: true,//this.vaildData(this.permission.xq_delete, false),
        editBtn: true,//this.vaildData(this.permission.xq_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    rowSave(row, done, loading) {
      if (!contrastTime(row.ksStart, row.ksEnd)) {
        this.$message({
          type: "warning",
          message: "开始时间不可大于结束时间!"
        });
        loading();
        return 0
      }
      row.kcIds = row.kcIds.toString()
      row.createTime = '2023-01-01'
      row.id = row.id === '' ? '0' : row.id
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (!contrastTime(row.ksStart, row.ksEnd)) {
        this.$message({
          type: "warning",
          message: "开始时间不可大于结束时间!"
        });
        loading();
        return 0
      }
      row.kcIds = row.kcIds.toString()
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: this.ids});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        // data.records.forEach(item => {
        //   item.xnId = item.xnName
        // })
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
      // const school = this.findObject(this.option.column, "schoolId");
      // school.hide = true;
    },
    //下载成绩导入模板
    handleTemplate() {
      // https://ossdata.kaibujiaoyu.com/images/202309011647040827.xlsx
      // window.open('https://ossdata.kaibujiaoyu.com/images/202309011647040827.xlsx');
      window.open('https://ossdata.kaibujiaoyu.com/images/202310081447066992.xlsx');
    },
    //导入成绩
    importGrades(row) {
      console.log(row)
      let excelFile = this.findObject(this.excelOption.column, "excelFile");
      excelFile.data.id = row.id
      this.excelForm = {}
      this.excelBox = true
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.onLoad(this.page);
      done();
      this.$message({
        type: "success",
        message: "导入成功!"
      });
      this.excelBox = false;
    },
    uploadBefore(file, done, loading, column) {
      console.log('导入成绩', file, column)
      this.$confirm("确定要导入成绩吗？如果之前已经导入成绩，将会删除之前的数据！", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        done()
      }).catch(() => {
        // done();
        this.excelBox = false;
      })
    },
    uploadError() {
      this.$message({
        type: "error",
        message: "导入排课失败，请稍后重试!"
      });
    },
    //发布成绩
    publishGrades(row) {
      let confirmMessage = row.status === 0 ? '确定发布成绩吗？' : '确定取消发布成绩吗？'
      this.$confirm(confirmMessage, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return issueOrCancelExamSore({id: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          // this.$refs.crud.toggleSelection();
        });
    },
    //跳转至成绩列表
    showView(row) {
      this.csId = row.id;
      //this.$refs.eps.onLoad({currentPage:1,pageSize:10});
      this.showMain = false;
      this.show = true;
    },
    showMainView() {
      this.showMain = true;
      this.show = false;
    },
  }
};
</script>

<style>
</style>
